import Vue from 'vue';
import axios from 'axios';
import routers from '@/router/routers';

import { setToken, getToken, getHTTP, setHTTP } from '@/libs/util';

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  // const { statusText, status, request: { responseURL } } = errorInfo;
  // let info = {
  //   type: 'ajax',
  //   code: status,
  //   mes: statusText,
  //   url: responseURL
  // };
  // 暂时没有错误日志上传
  // if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
};
const getProtocol = (str) => {
  const index = str.indexOf(':');
  const _http = str.substring(0, index);
  if (_http.indexOf('http') >= 0) {
    return _http;
  } else {
    return 'http';
  }
};
// const protocol = getProtocol(document.referrer);
const protocol = getProtocol(document.URL);
// console.log(document.URL,'当前浏览器地址document.URL');
// console.log(window.location.href,'当前浏览器地址');
// console.log(protocol,'protocol');
setHTTP(protocol);

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = getHTTP() + baseUrl;
    // this.baseUrl = baseUrl;
    console.log(baseUrl, 'baseUrl');
    this.queue = {};
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {},
      withCredentials: true
    };
    return config;
  }
  destroy (url) {
    // 将请求从请求序列中移除
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // console.log(getToken(), 'gettoken');
      // 添加全局的loading...
      if (getToken()) {
        config.headers['Authorization'] = getToken();
      }

      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      // 将请求添加至请求队列
      this.queue[url] = true;
      return config;
    }, error => {
      return Promise.reject(error);
    });
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url);
      const { data, status } = res;
      const { code, msg = '' } = data;

      // 后台的报错
      // eslint-disable-next-line eqeqeq
      if (code != 200) {
        if (code == 500) {
          Vue.prototype.$Message.error(msg);
          return Promise.reject(msg);
        }

        if (code == 1012) { // 登录过期，跳转到登录页
          setToken('');
          routers.push({
            name: 'login'
          });
        }
      }
      return { data, status };
    }, error => {
      this.destroy(url);
      let errorInfo = error.response;
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error));
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        };
      }

      // http 请求错误
      Vue.prototype.$Message.error(`${errorInfo.status}${errorInfo.statusText}`);

      addErrorLog(errorInfo);
      return Promise.reject(error);
    });
  }
  request (options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}
export default HttpRequest;
